package com.gzyj.jtt808.v2013.protocol;

import com.gzyj.jtt808.utils.HexBytesUtil;
import com.gzyj.jtt808.v2013.enums.BusinessDataType;
import com.gzyj.jtt808.v2013.enums.TerminalRegisterResult;
import com.gzyj.jtt808.v2013.Package;

import io.netty.buffer.ByteBuf;
import lombok.Data;

import java.io.Serializable;
import java.nio.charset.Charset;

/**
 * 终端注册应答
 *
 * @author lhj
 */
@Data
public class JTT808_0x8100 extends Package implements Serializable {

    private Integer AckMsgNum;//应答流水号 对应的终端注册消息的流水号
    private TerminalRegisterResult terminalRegisterResult;//结果
    private String Code;//鉴权码 只有在成功后才有该字段


    public JTT808_0x8100() {
        super(BusinessDataType.终端注册应答.getCode());
    }

    @Override
    public void encodeImpl(ByteBuf buf) {
        buf.writeShort(this.AckMsgNum);
        buf.writeByte(this.terminalRegisterResult.getCode());
        if (this.terminalRegisterResult == TerminalRegisterResult.成功) {
            buf.writeCharSequence(this.Code, Charset.forName("GBK"));
        }
    }

    @Override
    public JTT808_0x8100 decodeImpl(ByteBuf buf) {
        this.AckMsgNum = buf.readUnsignedShort();
        this.terminalRegisterResult = TerminalRegisterResult.find(Integer.parseInt(HexBytesUtil.bytesToHex(HexBytesUtil.readByOffset(buf, 1)), 16));
        if (this.terminalRegisterResult == TerminalRegisterResult.成功) {
            this.Code = new String(HexBytesUtil.readByOffset(buf, buf.readableBytes()), Charset.forName("GBK"));
        }


        return this;
    }
}
